<template>
  <div class="users">
    <!-- 顶部菜单区 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >添加卡片</el-button
          >
        </el-col>
      </el-row>
      <!-- 用户信息展示区 -->
      <el-table :data="userList" stripe border>
        <el-table-column type="index" label="-"> </el-table-column>
        <el-table-column prop="username" label="用户名"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="role_name" label="权限"> </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="switchChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="管理" width="180px">
          <template #default="scope">
            <el-tooltip content="编辑" placement="top" effect="dark">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-s-fold"
                @click="editUserDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="dark">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-delete"
                @click="deleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="角色管理" placement="top" effect="dark">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-setting"
                @click="settingRoleDialog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-size="queryInfo.pagesize"
        :page-sizes="[1, 3, 5, 7]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeDialog"
    >
      <el-form
        :model="addFormData"
        :rules="addFormRules"
        label-width="70px"
        ref="formRef"
      >
        <el-form-item prop="username" label="用户名">
          <el-input
            placeholder="请输入用户名"
            v-model="addFormData.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            placeholder="请输入密码"
            v-model="addFormData.password"
            show-password
          ></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input
            placeholder="请输入邮箱"
            v-model="addFormData.email"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机">
          <el-input
            placeholder="请输入手机号"
            v-model="addFormData.mobile"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogclose"
    >
      <el-form
        :model="editFormData"
        :rules="editFormRules"
        label-width="70px"
        ref="editFormRef"
      >
        <el-form-item prop="username" label="权限">
          <el-input v-model="editFormData.role_id" disabled></el-input>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input
            placeholder="请输入邮箱"
            v-model="editFormData.email"
          ></el-input>
        </el-form-item>
        <el-form-item prop="mobile" label="手机">
          <el-input
            placeholder="请输入手机号"
            v-model="editFormData.mobile"
          ></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(id)">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 权限管理 -->
    <el-dialog
      title="角色管理"
      :visible.sync="roleDialogVisible"
      width="50%"
      @close="roleDialogClose"
    >
      <div class="role-main-content">
        <p>用户名:{{ userInfo.username }}</p>
        <p>角色:{{ userInfo.role_name }}</p>
        <div>
          分配新角色
          <el-select v-model="selectedRoleId" placeholder="请选择一个角色">
            <el-option
              :label="item.roleName"
              v-for="item in rolesLost"
              :key="item.id"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmRoleAllocate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",
  data() {
    function emailValidate(rule, value, callback) {
      if (!/^[a-zA-Z][a-zA-Z0-9]{4,14}@.com/.test(value)) {
        callback("邮箱不符合规范");
      } else {
        callback();
      }
    }
    function mobileValidate(rule, value, callback) {
      if (!/^1[3,7,8,5][0-9]{9,9}$/.test(value)) {
        callback("手机号不符合规范");
      } else {
        callback();
      }
    }
    return {
      queryInfo: {
        query: "",
        pagenum: 1, //
        pagesize: 5
      },
      userList: [], //请求的数据
      total: 0, //请求的总数据数目
      dialogVisible: false, //控制对话框的显示和隐藏
      editDialogVisible: false,
      roleDialogVisible: false, //角色管理对话框
      userInfo: {}, //每个角色的信息
      id: "", //修改用户的id
      //对话框的添加用户的表单数据
      addFormData: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //对话框添加用户验证规则
      addFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 4,
            max: 10,
            message: "用户名只能是4-10位之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: emailValidate, trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 4,
            max: 10,
            message: "密码只能是4-10位之间",
            trigger: "blur"
          }
        ],
        mobile: [
          { required: true, message: "密码没有输入", trigger: "blur" },
          { validator: mobileValidate, trigger: "blur" }
        ]
      },
      editFormData: {
        id: "",
        username: "",
        mobile: "",
        email: ""
      },
      editFormRules: {
        username: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 4,
            max: 10,
            message: "用户名只能是4-10位之间",
            trigger: "blur"
          }
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: emailValidate, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          { validator: mobileValidate, trigger: "blur" }
        ]
      },
      rolesLost: [],
      selectedRoleId: "" //select的下拉框显示的角色id 注意的是显示的是名字 因为名字是根据vaule定义的label渲染的
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    //请求数据
    async getUsers() {
      try {
        let { data: res } = await this.$http.get("users", {
          params: this.queryInfo
        });
        this.userList = res.data.users;
        this.total = res.data.total;
        // console.log(res);
      } catch (err) {
        console.log(err);
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getUsers();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      console.log(newPage);
      this.getUsers();
    },
    async switchChange(data) {
      // console.log(data)
      let { data: res } = await this.$http.put(
        `users/${data.id}/state/${data.mg_state}`
      );
      if (res.meta.status == 200) {
        this.$message.success("状态修改成功");
      } else {
        this.$message.error("状态修改失败");
      }
    },
    // 关闭对话框触发的事件 使得form表单刷新
    closeDialog() {
      this.$refs.formRef.resetFields();
    },
    //添加用户的安妮的点击
    addUser() {
      this.$refs.formRef.validate(valid => {
        //valid为验证的结果
        if (!valid) {
          //若没通过 则直接返回 不传给后台
          return;
        } else {
          //发送添加用户请求
          this.$http.post("users", this.addFormData).then(res => {
            if (res.data.meta.status != 201) {
              this.$message.error("添加失败");
            } else {
              //添加成功做三个事  页面提示 关闭对话框 刷新数据
              this.$message.success("添加成功");
              this.dialogVisible = false;
              this.getUsers();
            }
          });
        }
      });
    },
    //点击编辑按钮弹出对话框
    editUserDialog(id) {
      this.editDialogVisible = true;
      this.id = id;
      //首先获取这一用户的信息将其填入对话框里
      this.$http
        .get("users/" + id)
        .then(res => {
          if (res.data.meta.status == 200) {
            //将数据添加到编辑对话框里
            this.editFormData = res.data.data;
            console.log(this.editFormData);
          } else {
            return;
          }
        })
        .catch(err => console.log(err));
    },
    editUser(id) {
      this.$refs.editFormRef.validate(valid => {
        if (valid) {
          this.$http
            .put("users/" + id, {
              email: this.editFormData.email,
              mobile: this.editFormData.mobile
            })
            .then(res => {
              if (res.data.meta.status != 200) {
                this.$message.error("修改失败");
              } else {
                this.$message.success("修改成功!");
                this.editDialogVisible = false;
                this.getUsers();
              }
            })
            .catch(err => console.log(err));
        } else {
          return;
        }
      });
    },
    editDialogclose() {
      this.$refs.editFormRef.resetFields();
    },
    //删除用户
    deleteUser(id) {
      //返回的是结果是在用户点了确定或取消之后
      this.$confirm("将会删除用户,are you sure", "注意!", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(res => {
          if (res == "confirm") {
            this.$http
              .delete("users/" + id)
              .then(res => {
                if (res.data.meta.status == 200) {
                  this.$message.success("删除成功");
                  this.getUsers();
                } else {
                  return;
                }
              })
              .catch(err => err);
          } else {
            return;
          }
        })
        .catch(err => console.log(err));
    },
    //角色管理对话
    settingRoleDialog(role) {
      // console.log(role)
      this.roleDialogVisible = true;
      (this.userInfo = role),
        this.$http
          .get("roles")
          .then(res => {
            if (res.data.meta.status == 200) {
              this.rolesLost = res.data.data;
            } else {
              this.$message.success("获取失败");
            }
          })
          .catch(err => err);
    },
    //确认角色分配
    confirmRoleAllocate() {
      let id = this.userInfo.id;
      //若选择则进行更改角色
      if (this.selectedRoleId) {
        this.$http
          .put(`users/${id}/role`, {
            rid: this.selectedRoleId
          })
          .then(res => {
            if (res.data.meta.status == 200) {
              this.$message.success("更改角色成功");
              this.getUsers();
              this.roleDialogVisible = false;
            } else {
              this.$message.error("失败了");
              this.roleDialogVisible = false;
            }
          })
          .catch(err => err);
      } else {
        return;
      }
    },
    //角色管理对话框关闭时
    roleDialogClose() {
      this.selectedRoleId = "";
    }
  }
};
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  margin-bottom: 20px;
}
.el-card {
  box-shadow: 0 0 1px rgba(0, 0, 0, 0.15);
}
.el-table {
  margin-top: 20px;
}
</style>
